﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.Text;
using System;
/// <summary>
/// 客户端
/// </summary>
public class GameClient
{
    //服务器地址
    private string serverAddress;
    //服务器端口
    private int port;
    //当前tcp客户端
    public TcpClient localClient;
    //接收服务器消息的线程
    private Thread receiveThread;
    int[] result;

    /// <summary>
    /// 构造方法
    /// </summary>
    public GameClient(string serverAddress,int port)
    {
        this.serverAddress = serverAddress;
        this.port = port;
    }
    /// <summary>
    /// 关闭客户端
    /// </summary>
    public void Close()
    {
        if (localClient!=null)
        {
            localClient.Close();
        }
        if (receiveThread!=null)
        {
            receiveThread.Abort();
        }
    }
    /// <summary>
    /// 启动客户端
    /// </summary>
    /// <returns></returns>
    public bool Start()
    {
        localClient = new TcpClient();
        try
        {
            localClient.Connect(IPAddress.Parse(serverAddress),port);

            receiveThread = new Thread(SocketReceiver);
            receiveThread.Start();
            Debug.Log("客户端启动");
        }
        catch (System.Exception ex)
        {
            Debug.Log("客户端连接服务器异常:"+ex.Message);
            if (!localClient.Connected)
            {
                return false;
            }
        }
        SendMsg(new int[] { 3,0,0,0,0,0});
        return true;
    }
    /// <summary>
    /// 客户端检测接收的服务器信息
    /// </summary>
    private void SocketReceiver()
    {
        if (localClient!=null)
        {
            int bufferSize = 8192;
            byte[] resultBuffer = new byte[bufferSize];
            do
            {
                try
                {
                    int byteRead = localClient.Client.Receive(resultBuffer);
                    if (byteRead == 0)
                    {
                        Debug.Log("与服务器连接中断");
                        break;
                    }
                    int firstInt = NetWorkUtils.ParseFirstInt(resultBuffer);
                    string[] sArray;
                    string username;
                    string password;
                    bool loginresult;
                    bool registerresult;
                    switch (firstInt)
                    {
                        case 0:
                            //处理接收到的数据
                            result = BytesToInt(resultBuffer, 0);
                            //具体处理接受信息的数据
                            for (int i = 0; i < GameManager.Instance.gameCodeReceive.Length; i++)
                            {
                                GameManager.Instance.gameCodeReceive[i] = result[i];
                            }
                            GameManager.Instance.receiveNewCode = true;
                            break;
                        case 1:
                            //处理接收到的数据
                            result = BytesToInt(resultBuffer, 0);
                            //具体处理接受信息的数据
                            for (int i = 0; i < GameManager.Instance.gameCodeReceive.Length; i++)
                            {
                                GameManager.Instance.gameCodeReceive[i] = result[i];
                            }
                            GameManager.Instance.receiveNewCode = true;
                            break;
                        case 2:
                            //处理接收到的数据
                            result = BytesToInt(resultBuffer, 0);
                            //具体处理接受信息的数据
                            for (int i = 0; i < GameManager.Instance.gameCodeReceive.Length; i++)
                            {
                                GameManager.Instance.gameCodeReceive[i] = result[i];
                            }
                            GameManager.Instance.receiveNewCode = true;
                            break;
                        case 4:
                            UIManager.Instance.LoginSuccess();
                            break;
                        case 5:
                            UIManager.Instance.LoginFail();
                            break;
                        case 8:
                            UIManager.Instance.RegisterSuccess();
                            break;
                        case 9:
                            UIManager.Instance.RegisterFail();
                            break;
                            //GameManager.Instance.ParseGameCode();
                            //string msg = Encoding.UTF8.GetString(resultBuffer, 0, byteRead);
                            //Debug.Log(msg);
                    }
                }
                catch (System.Exception ex)
                {
                    Debug.Log("客户端接收数据异常" + ex.Message);
                    Close();
                }
            } while (true);
        }
    }
    /// <summary>
    /// int数组转byte数组
    /// </summary>
    private byte[] IntToBytes(int[] src, int offset)
    {
        byte[] values = new byte[src.Length * 4];
        for (int i = 0; i < src.Length; i++)
        {
            values[offset] = (byte)src[i];
            values[offset + 1] = (byte)(src[i] >> 8);
            values[offset + 2] = (byte)(src[i] >> 16);
            values[offset + 3] = (byte)(src[i] >> 24);
            offset += 4;
        }
        return values;
    }
    /// <summary>
    /// byte数组转int数组
    /// </summary>
    /// <returns></returns>
    private int[] BytesToInt(byte[] src, int offset)
    {
        int[] values = new int[src.Length / 4];
        for (int i = 0; i < src.Length / 4; i++)
        {
            int value = (int)(src[offset] & 0xFF)
                | (int)(src[offset + 1] & 0xFF << 8)
                | (int)(src[offset + 2] & 0xFF << 16)
                | (int)(src[offset + 3] & 0xFF << 24);
            values[i] = value;
            offset += 4;
        }
        return values;
    }

    /// <summary>
    /// 发送信息
    /// </summary>
    public void SendMsg(int[] gameCode)
    {
        if (localClient != null)
        {
            localClient.Client.Send(IntToBytes(gameCode,0));
        }
    }

    public void SendMsg(byte[] msg)
    {
        if (localClient != null)
        {
            localClient.Client.Send(msg);
        }
    }

    private int ParseFirstInt(byte[] src, int offset)
    {
        int result = (int)(src[offset] & 0xFF)
                | (int)(src[offset + 1] & 0xFF << 8)
                | (int)(src[offset + 2] & 0xFF << 16)
                | (int)(src[offset + 3] & 0xFF << 24);
        return result;
    }

    public byte[] addFirstInt(byte[] src, int firstInt)
    {
        byte firstByte = (byte)firstInt;
        byte[] firstIntBytes = oneIntToBytes(firstByte);
        byte[] result = new byte[src.Length + firstIntBytes.Length];
        Array.Copy(firstIntBytes, 0, result, 0, firstIntBytes.Length);
        Array.Copy(src, 0, result, src.Length, src.Length);
        return result;
    }

    public byte[] oneIntToBytes(int i)
    {
        byte[] intBytes = new byte[4];
        intBytes[0] = (byte)i;
        intBytes[1] = (byte)(i >> 8);
        intBytes[2] = (byte)(i >> 16);
        intBytes[3] = (byte)(i >> 24);
        return intBytes;
    }
}
